package com.kk.prototype;

import java.io.*;

/**
 * @author 王志强
 * @date 2021-12-14
 */
public class Sleep implements Cloneable, Serializable {
    public Sleep friend;
    private String name;
    private Integer age;
    private String address;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "Sleep{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", address='" + address + '\'' +
                '}';
    }

    @Override
    protected Object clone() {

        Sleep sleep = null;
        try {
            sleep = (Sleep) super.clone();
        } catch (CloneNotSupportedException e) {
            System.out.println("克隆失败！");
            System.out.println(e.getMessage());
        }
        return sleep;
    }


    /**
     * 深拷贝 - 通过对象的序列化实现
     */
    public Object deepClone() throws IOException {

        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;
        try {
            //序列化
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            //当前对象以对象流的方式输出
            oos.writeObject(this);

            //反序列化
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            Sleep deepClone = (Sleep) ois.readObject();

            return deepClone;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ois != null) {
                ois.close();
            }
            if (bis != null) {
                bis.close();
            }
            if (oos != null) {
                oos.close();
            }
            if (bos != null) {
                bos.close();
            }
        }
        return null;
    }
}
